<?php
/**
 * 功能: 用户管理
 * User: 文丹
 * Date: 2018/7/9 0009
 * Time: 10:20
 */

namespace app\index\controller;
use app\validate\Positive;
use think\Controller;
use think\Db;
use think\Session;

class User extends Controller{
    /**
     * 个人信息展示
     */
    public function index(){
        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'token不能为空','ok'=>false]);
        }

        $user = model('User')->getUser($token);
        if($user){
            return json(['msg'=>'请求成功！','ok'=>true,'user'=>$user]);
        }else{
            return json(['msg'=>'请求出错','ok'=>false]);
        }
    }
    /**
     * 个人信息设置
     */
    public function set_up(){
        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'token不能为空','ok'=>false]);
        }

        $user    = model('User')->getUser($token);
        $user_id = $user['id'];
        if($user){
            $photo = trim(input('photo',$user['photo']));
            $nickname = trim(input('nickname',$user['nickname']));
            $sex = intval(input('sex',1));
            $data = ['photo'=>$photo,'nickname'=>$nickname,'sex'=>$sex];
            $result = model('User')->saveUser($data,$user_id);
            if($result){
                return json(['msg'=>'设置成功','ok'=>true]);
            }else{
                return json(['msg'=>'设置失败','ok'=>false]);
            }
        }else{
            return json(['msg'=>'token失效或者您未登录','ok'=>false,'code'=>501]);
        }


    }

    /**
     * 绑定支付宝
     */
    public function alipay(){
        $token = trim(input('token'));
        $truename = trim(input('truename'));
        $account  = trim(input('ali_account'));
        $ali_phone  = trim(input('ali_phone'));
        $verify  = trim(input('verify'));
        $code =  useful_time(35);
        if($verify == $code){
            $result = model('User')->getUser($token);
            if($result){
                $data = [
                    'truename'=>$truename,
                    'ali_account'=>$account,
                    'ali_phone'=>$ali_phone
                ];
                $res = Db::name('user')->where('token',$token)->update($data);
                if($res){
                    Session::delete('phone');
                    Session::delete('code');
                    Session::delete('time');
                    return json(['msg'=>'绑定成功','ok'=>true]);
                }else{
                    return json(['msg'=>'您已经绑定过了','ok'=>false]);
                }
            }else{
                return json(['msg'=>'您还未登录','ok'=>false]);
            }
        }else{
            return json(['msg'=>'验证码错误','ok'=>false]);
        }
    }

    /**
     * 绑定微信
     */
    public function weix(){
        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'token不能为空','ok'=>false]);
        }

        $user    = model('User')->getUser($token);
        $user_id = $user['id'];
        $openid = trim(input('openid'));
        $w_nickname = trim(input('nickname'));
        $w_photo = trim(input('photo'));
        if(empty($openid)||empty($w_nickname)||empty($w_photo)){
            return json(['msg'=>'数据信息不完整！','ok'=>false]);
        }
        $user = Db::name('user')->where('id',$user_id)->where('openid',$openid)->find();
        if($user){
          return json(['msg'=>'已经绑定过微信了！','ok'=>false]);

        }else{

            /**
             * 微信账号不存在
             */
            $data = [
                'openid'=>$openid,
                'w_nickname'=>$w_nickname,
                'w_photo'=>$w_photo,
            ];

            $res = Db::name('user')->where('id',$user_id)->update($data);
            if($res){
                return json(['msg'=>'绑定成功！','ok'=>true]);
            }else{
                return json(['msg'=>'绑定失败，请稍后再试~！','ok'=>false]);
            }

        }
    }

    /**
     * 微信解绑
     */
    public function weix_remove(){
        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'token不能为空','ok'=>false]);
        }

        $user    = model('User')->getUser($token);
        $user_id = $user['id'];
        $data = [
            'openid'=>'',
            'w_nickname'=>'',
            'w_photo'=>'',
        ];
        $res = Db::name('user')->where('id',$user_id)->update($data);
        if($res){
            return json(['msg'=>'解绑成功！','ok'=>true]);
        }else{
            return json(['msg'=>'解绑失败，请稍后再试~！','ok'=>false]);
        }
    }


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * TODO:申请成为合伙人（待修改）
     */
    public function partner(){
        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'token不能为空','ok'=>false]);
        }

        $user = model('User')->getUser($token);
        $user_id = $user['id'];

        if($user){
            $is_partner = Db::name('user')->where('id',$user_id)->value('is_partner');
            if($is_partner ==1){
                return json(['msg'=>'您已经是合伙人了，不能再申请了','ok'=>false]);
            }

            $a = getRandomString(6);
            $check_mark = Db::name('user')->where('mark',$a)->find();
            $n = '';
            if($check_mark){
                $n = getRandomString(6);
                $a = $n;
            }
            $check = Db::name('goods_order')->where('user_id',$user_id)->find();
            if($check){
                $result = Db::name('user')->where('id',$user_id)->update(['is_partner'=>1,'mark'=>$a,'status'=>3]);
                //echo $result;
                if($result){
                    return json(['msg'=>'已成为合伙人','ok'=>true]);
                }else{
                    return json(['msg'=>'您已经是合伙人了，不能再申请了','ok'=>false]);
                }
            }else{
                return json(['msg'=>'使用【买就省APP】至少购物一次，才可申请成为合伙人','ok'=>false]);
            }

        }else{
            return json(['msg'=>'token失效或还未登录','ok'=>false]);
        }

    }

    /**
     * 合伙人视频介绍
     */
    public function video(){
        $video = Db::name('partner')->find();
        if($video){
            return json(['msg'=>'请求成功','ok'=>true,'data'=>$video]);
        }else{
            return json(['msg'=>'暂无数据','ok'=>false]);
        }
    }

    /**
     * 修改密码
     */
    public function save_pwd(){
        $code =  useful_time(35);
        $verify = trim(input('verify'));
        $token = trim(input('token'));
        $old   = trim(input('old'));
        $new   = trim(input('new'));
        if($code){
            if($verify!=$code){
                return json(['msg'=>'验证码错误','ok'=>false]);
            }else{
                if(empty($token)){
                    return json(['msg'=>'token不能为空','ok'=>false]);
                }
                if(empty($old)||empty($new)){
                    return json(['msg'=>'请填写完整的数据','ok'=>false]);
                }

                $user = model('User')->getUser($token);
                $user_id = $user['id'];
                if(empty($user)){
                    return json(['msg'=>'您未登录，或者登录被占用','ok'=>false]);
                }
                $check = Db::name('user')->where('password',md5($old))->where('id',$user_id)->find();
                if($check){
                    $res = Db::name('user')->where('id',$user_id)->where('password',md5($old))->update(['password'=>md5($new)]);
                    if($res){
                        return json(['msg'=>'修改成功','ok'=>true]);
                    }else{
                        return json(['msg'=>'修改失败','ok'=>false]);
                    }
                }else{
                    return json(['msg'=>'原密码错误','ok'=>false]);
                }
            }

        }else{
            return json(['msg'=>'验证码失效','ok'=>false]);
        }




    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * 我的粉丝
     */
    public function fans(){
        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'token不能为空','ok'=>false]);
        }

        $user    = model('User')->getUser($token);
        $user_id = $user['id'];
        if(empty($user_id)){
            return json(['msg'=>'用户未登录或者登录失效','ok'=>false]);
        }

        //粉丝累计数
        $member = Db::name('user')->where('id',$user_id)->value('member');

        //粉丝返利金额
        $rebate = Db::name('user')->where('id',$user_id)->value('rebate');

        $level1  = Db::name('user')
            ->where('parent_id',$user_id)
            ->field('id,phone,nickname,photo,commission,member,add_time,parent_id,status,is_partner')
            ->paginate(20);//一级粉丝

        $level2 = [];
        if(!empty($level1)){
            foreach($level1 as $k=>$v){
                $l2 = Db::name('user')
                    ->where('parent_id',$v['id'])
                    ->field('id,phone,nickname,photo,commission,member,add_time,parent_id,status,is_partner')
                    ->paginate(20);;//二级粉丝
                if($l2){
                    $level2 =   $l2;
                }

            }
        }else{
            $level2 = [];
        }
        if(!empty($level1)||!empty($level2)||!empty($valid)||!empty($invalid)){
            return json([
                'msg'=>'请求成功！',
                'ok'=>true,
                'data'=>[
                    'member'=>$member,//粉丝数
                    'level1'=>$level1,
                    'level2'=>$level2,

                ]
            ]);
        }else {
            return json(['msg' => '暂无粉丝！', 'ok' => false]);
        }


    }
    /**
     * 申请提现
     */
    public function apply(){
        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'token不能为空','ok'=>false]);
        }
        $user    = model('User')->getUser($token);
        $user_id = $user['id'];
        $amount  = trim(input('amount'));
        if($amount<1){
            return json(['msg'=>'提现金额不得小于1元','ok'=>false]);
        }
        $yue = $user['commission'] - $amount;
        if($yue <= $user['freeze']){
            return json(['msg'=>'上月的佣金，在次月的25号才可提现。','ok'=>false]);
        }

        $check   = (new Positive())->goCheck();
        if(!$check){
            $total   = Db::name('user')->where('id',$user_id)->value('commission');
            if($total<$amount){
                return json(['msg'=>'申请数大于总金额数，不能提现','ok'=>false]);
            }

            $data = [
                'user_id'=>$user_id,
                'amount'=>$amount,
                'apply_time'=>time()
            ];

            // 启动事务
            Db::startTrans();
            try{
                Db::table('cash')->insert($data);
                Db::table('user')->where('id',$user_id)->setDec('commission',$amount);

                // 提交事务
                Db::commit();
                return json(['msg'=>'提交成功，请等待审核','ok'=>true]);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['msg'=>'提交失败，请稍后再试','ok'=>false]);
            }

        }else{
            return $check;
        }

    }

    /**
     * 提现 显示
     */
    public function amount(){
        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'token不能为空','ok'=>false]);
        }
        $user    = model('User')->getUser($token);
        $user_id = $user['id'];
        if(empty($user_id)){
            return json(['msg'=>'您还未登录或者登录被占用','ok'=>false]);
        }
        /*dump($user_id);
        die;*/
        $yu      = $user['commission']-$user['freeze'];//可提现余额
        //正在提取
        $extract    = Db::name('cash')
            ->where('user_id',$user_id)
            ->where('state',1)
            ->sum('amount');

        //待结算
        $settle = $user['freeze'];
        $data = [
            'commission'=>$user['commission'],//收入金额
            'yu'=>$yu,//可提现余额
            'extract'=>$extract,//正在提取
            'settle'=>$settle,//待结算
        ];
        return json(['msg'=>'请求成功','ok'=>true,'data'=>$data]);


    }

   //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * 合伙人 - 收益
     */
    public function partner_profit(){
        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'token不能为空','ok'=>false]);
        }
        $user    = model('User')->getUser($token);
        $user_id = $user['id'];
        if(empty($user_id)){
            return json(['msg'=>'你还未登录，或者登录被占用','ok'=>false,'code'=>501]);
        }

        if($user['is_partner']==1){
            //合伙人
            //今日
            $BeginDate = date('Y-m-d');
            $endDate   = $BeginDate." 23:59:59";
            $today_pay = model('User')->getPay($token,$BeginDate,$endDate);
            $today_yj  = model('User')->getYj($token,$BeginDate,$endDate);

            //本月
            $Begin= date('Y-m-01', strtotime(date("Y-m-d")));//当月第一天
            $end1 = date('Y-m-d', strtotime("$Begin +1 month -1 day"));//当月最后一天
            $end = $end1." 23:59:59";//当月最后一天
            $mouth_pay = model('User')->getPay($token,$Begin,$end);
            $mouth_yj  = model('User')->getYj($token,$Begin,$end);

            return json([
                'msg'=>'请求成功',
                'ok'=>true,
                'today_pay'=>$today_pay,//今日付款笔数
                'today_yj'=>$today_yj,
                'mouth_pay'=>$mouth_pay,
                'mouth_yj'=>$mouth_yj,//本月预估佣金
                'is_partner'=>1,
            ]);
        }else{
            return json([
                'msg'=>'请求成功,该用户不是合伙人',
                'ok'=>true,
                'is_partner'=>0,
            ]);
        }

    }

    /**
     * 提现记录
     */
    public function cash_record(){
        $token = trim(input('token'));
        if (empty($token)) {
            return json(['msg' => 'token不能为空', 'ok' => false]);
        }
        $user = model('User')->getUser($token);
        $user_id = $user['id'];
        $limit = 20;
        $page = intval(input('page'));
        $record = Db::name('cash')
            ->where('user_id',$user_id)
            ->order('apply_time desc')
            ->field('id,amount,apply_time,deal_time,remark')
            ->select();
        if ($record) {
            $res = array_slice($record, ($page - 1) * $limit, $limit);
            return json([
                'msg' => '请求成功',
                'ok' => true,
                'data' => $res

            ]);
        } else {
            return json([
                'msg' => '暂无提现记录',
                'ok' => false
            ]);

        }
    }

    /**
     * 粉丝订单
     */
    public function fans_order(){
        $token = trim(input('token'));
        $item  = intval(input('item',0));//0全部，1待返，2已返，3退款
        if (empty($token)) {
            return json(['msg' => 'token不能为空', 'ok' => false]);
        }
        $user = model('User')->getUser($token);
        $user_id = $user['id'];
        $page  = input('page',1);
        $limit  = 20;
        $status = $user['status'];//1，普通用户，2,一般合伙人，3初级合伙人，4,高级合伙人
        $partner_rule = Db::name('rebate_rule')->where('us_id',$status)->find();
        $res1 = Db::name('user')->where('parent_id',$user_id)->select();//一级粉丝
     /*  print_r($res1);
      //  dump($res1);
        die;*/
        $order = [];
        if($res1){
            $ids1 = [];
            $ids2 = [];
            if($item==0){
                foreach($res1 as $k=>$v){
                    $ids1[] = $v['id'];
                    $res2 = Db::name('user')->where('parent_id',$v['id'])->select();
                    if($res2) {
                        foreach ($res2 as $k1 => $v1) {
                            $ids2[] = $v1['id'];
                        }
                    }

                }
              //  dump($ids1);
                if($ids1){
                    $or11 = Db::name('goods_order')
                        ->whereIn('user_id',$ids1)
                        ->order('id desc')
                        ->field('info,create_time,order_num,pay,settle,yj_sum,goods_id,member_actual,member_expect,user_id')
                        ->select();
                    $or1 = [];
                        foreach($or11 as $k=>$v){
                            $or1[$k] = $v;
                            $rate = $partner_rule['level1']/100;
                            $or1[$k]['royalty_yj'] = $v['member_expect']*$rate;
                        }
                }else{
                    $or1 = [];
                }
                if($ids2){
                    $or22 = Db::name('goods_order')
                        ->whereIn('user_id',$ids2)
                        ->order('id desc')
                        ->field('info,create_time,order_num,pay,settle,yj_sum,goods_id,member_actual,member_expect,user_id')
                        ->select();
                    $or2 = [];
                    foreach($or22 as $k=>$v){
                        $or2[$k] = $v;
                        $rate = $partner_rule['level2']/100;
                        $or2[$k]['royalty_yj'] = $v['member_expect']*$rate;
                    }
                }else{
                    $or2 = [];
                }

                $order = array_merge($or1,$or2);

            }elseif($item==1){
                //待返
                $ids1 = [];
                $ids2 = [];
                foreach($res1 as $k=>$v){
                    $ids1[] = $v['id'];
                    $res2 = Db::name('user')->where('parent_id',$v['id'])->select();
                    if($res2){
                        foreach($res2 as $k1=>$v1){
                            $ids2[] = $v1['id'];
                        }
                    }
                }
                if($ids1){
                    $or11 = Db::name('goods_order')
                        ->whereIn('user_id',$ids1)
                        ->where('state',1)
                        ->order('id desc')
                        ->field('info,create_time,order_num,pay,settle,yj_sum,goods_id,member_actual,member_expect')
                        ->select();
                    $or1 = [];
                    foreach($or11 as $k=>$v){
                        $or1[$k] = $v;
                        $rate = $partner_rule['level1']/100;
                        $or1[$k]['royalty_yj'] = $v['member_expect']*$rate;
                    }
                }else{
                    $or1 = [];
                }
                if($ids2){
                    $or22 = Db::name('goods_order')
                        ->whereIn('user_id',$ids2)
                        ->where('state',1)
                        ->order('id desc')
                        ->field('info,create_time,order_num,pay,settle,yj_sum,goods_id,member_actual,member_expect')
                        ->select();
                    $or2 = [];
                    foreach($or22 as $k=>$v){
                        $or2[$k] = $v;
                        $rate = $partner_rule['level2']/100;
                        $or2[$k]['royalty_yj'] = $v['member_expect']*$rate;
                    }
                }else{
                    $or2 = [];
                }

                $order = array_merge($or1,$or2);
            }elseif($item==2){
                //已返
                $ids1 = [];
                $ids2 = [];
                foreach($res1 as $k=>$v){
                    $ids1[] = $v['id'];
                    $res2 = Db::name('user')->where('parent_id',$v['id'])->select();
                    if($res2){
                        foreach($res2 as $k1=>$v1){
                            $ids2[] = $v1['id'];
                        }
                    }
                 }
                if($ids1){
                    $or11 = Db::name('goods_order')
                        ->whereIn('user_id',$ids1)
                        ->where('state',2)
                        ->order('id desc')
                        ->field('info,create_time,order_num,pay,settle,yj_sum,goods_id,member_actual,member_expect')
                        ->select();
                    $or1 = [];
                    foreach($or11 as $k=>$v){
                        $or1[$k] = $v;
                        $rate = $partner_rule['level1']/100;
                        $or1[$k]['royalty_yj'] = $v['member_actual']*$rate;
                    }
                }else{
                    $or1 = [];
                }
                if($ids2){
                    $or22 = Db::name('goods_order')
                        ->whereIn('user_id',$ids2)
                        ->where('state',2)
                        ->order('id desc')
                        ->field('info,create_time,order_num,pay,settle,yj_sum,goods_id,member_actual,member_expect')
                        ->select();
                    $or2 = [];
                    foreach($or22 as $k=>$v){
                        $or2[$k] = $v;
                        $rate = $partner_rule['level2']/100;
                        $or2[$k]['royalty_yj'] = $v['member_actual']*$rate;
                    }
                }else{
                    $or2 = [];
                }
                $order = array_merge($or1,$or2);
            }elseif($item==3){
                //退款（维权）
                $ids1 = [];
                $ids2 = [];
                foreach($res1 as $k=>$v){
                    $ids1[] = $v['id'];
                    $res2 = Db::name('user')->where('parent_id',$v['id'])->select();
                    if($res2){
                        foreach($res2 as $k1=>$v1){
                            $ids2[] = $v1['id'];
                        }
                    }
                }
                if($ids1){
                    $or11 = Db::name('order_refund')
                        ->whereIn('user_id',$ids1)
                        ->order('id desc')
                        ->select();
                    $or1 = [];
                    foreach($or11 as $k=>$v){
                        $or1[$k] = $v;
                        $rate = $partner_rule['level1']/100;
                        $or1[$k]['royalty_yj'] = $v['fact']*$rate;
                    }
                }else{
                    $or1 = [];
                }
                if($ids2){
                    $or22 = Db::name('order_refund')
                        ->whereIn('user_id',$ids2)
                        ->order('id desc')
                        ->select();
                    $or2 = [];
                    foreach($or22 as $k=>$v){
                        $or2[$k] = $v;
                        $rate = $partner_rule['level2']/100;
                        $or2[$k]['royalty_yj'] = $v['fact']*$rate;
                    }
                }else{
                    $or2 = [];
                }

                $order = array_merge($or1,$or2);
            }


        }else{
            $order = [];
        }
      /*print_r($order);
           dump($order);
           die;*/
        if($order){
            $result = array_slice($order,($page-1)*$limit,$limit);
            $arr = [];
            foreach($result as $k=>$v){
                $arr[$k] = $v;
                $arr[$k]['yj_sum'] = round($v['yj_sum']/2,2);
                $goods = Db::name('goods')->where('goods_id',$v['goods_id'])->value('goods_big_img');
                if($goods){
                    $arr[$k]['image']  = $goods;
                }else{
                    $arr[$k]['image']  = null;
                }

            }
            return json([
                'msg' => '请求成功',
                'ok' => true,
                'data' => $arr

            ]);
        }else{
            return json([
                'msg' => '暂无数据',
                'ok' => false
                ]);
        }
    }

    /**
     * 我的订单
     */
    public function my_order(){
        $token = trim(input('token'));
        $page  = intval(input('page'));
        $limit = 20;
        if (empty($token)) {
            return json(['msg' => 'token不能为空', 'ok' => false]);
        }
        $user = model('User')->getUser($token);
        $user_id = $user['id'];
        $order = Db::name('goods_order')
            ->where('user_id',$user_id)
            ->order('id desc')
            ->field('info,create_time,order_num,pay,settle,yj_sum,goods_id,member_expect,user_id')
            ->paginate($limit)
            ->each(function($item,$key){

                $item['yj_sum'] = round($item['yj_sum']/2,2);

                $goods = Db::name('goods')->where('goods_id',$item['goods_id'])->find();
                if($goods){
                    $item['image']  = $goods['goods_big_img'];
                }else{
                    $item['image']  = null;
                    $item['member_yongjin']  = 0;

                }
                return $item;
            });

        if($order){
            return json(['msg' => '请求成功', 'ok' => true,'data'=>$order]);
        }else{
            return json(['msg' => '暂无订单', 'ok' => false]);
        }
    }

    /**
     * 待返
     */
    public function back(){
        $token = trim(input('token'));
        $page  = intval(input('page'));
        $limit = 20;
        if (empty($token)) {
            return json(['msg' => 'token不能为空', 'ok' => false]);
        }
        $user = model('User')->getUser($token);
        $user_id = $user['id'];
        $order = Db::name('goods_order')
            ->where('user_id',$user_id)
            ->where('state',1)
            ->order('id desc')
            ->field('info,create_time,order_num,pay,settle,yj_sum,goods_id,member_actual,member_expect')
            ->paginate($limit)
            ->each(function($item,$key){
                $item['yj_sum'] = round($item['yj_sum']/2,2);
                $goods = Db::name('goods')->where('goods_id',$item['goods_id'])->value('goods_big_img');
                if($goods){
                    $item['image']  = $goods;
                }else{
                    $item['image']  = null;
                }
                return $item;
            });

        if($order){
            return json(['msg' => '请求成功', 'ok' => true,'data'=>$order]);
        }else{
            return json(['msg' => '暂无订单', 'ok' => false]);
        }
    }

    /**
     * 已返
     */
    public function returned(){
        $token = trim(input('token'));
        $page  = intval(input('page'));
        $limit = 20;
        if (empty($token)) {
            return json(['msg' => 'token不能为空', 'ok' => false]);
        }
        $user = model('User')->getUser($token);
        $user_id = $user['id'];
        $order = Db::name('goods_order')
            ->where('user_id',$user_id)
            ->where('state',2)
            ->order('id desc')
            ->field('info,create_time,order_num,pay,settle,yj_sum,goods_id')
            ->paginate($limit)
            ->each(function($item,$key){
                $item['yj_sum'] = round($item['yj_sum']/2,2);
                $goods = Db::name('goods')->where('goods_id',$item['goods_id'])->value('goods_big_img');
                if($goods){
                    $item['image']  = $goods;
                }else{
                    $item['image']  = null;
                }
                return $item;
            });
        if($order){
            return json(['msg' => '请求成功', 'ok' => true,'data'=>$order]);
        }else{
            return json(['msg' => '暂无订单', 'ok' => false]);
        }
    }
    /**
     * 维权/退款
     */
    public function refund(){
        $token = trim(input('token'));
        $page  = intval(input('page'));
        $limit = 20;
        if (empty($token)) {
            return json(['msg' => 'token不能为空', 'ok' => false]);
        }
        $user = model('User')->getUser($token);
        $user_id = $user['id'];

        $refund = Db::name('order_refund')->order('id desc')->where('user_id',$user_id)->paginate($limit);
        if($refund){
            return json(['msg' => '请求成功', 'ok' => true,'data'=>$refund]);
        }else{
            return json(['msg' => '暂无数据', 'ok' => false]);
        }
    }


    /**
     * 订单状态定时修改
     */
    public function state(){
        $token = trim(input('token'));
        $user = model('User')->getUser($token);
        $user_id = $user['id'];

        $order = Db::name('goods_order')
            ->where('state',1)
            ->where('user_id',$user_id)
            ->select();
        /*dump($order);
        die;*/

        if($order){
            foreach($order as $key =>$value){

                $a     = strtotime('-20 minute');
                $time  = date($value['create_time'],$a);
                $time1 = urlencode($time);
                $vkey  = config('vkey');
                $url   = "http://api.vephp.com/order?vekey=".$vkey."&start_time=".$time1."&span=1200";
                $data  = file_get_contents($url);
                $res   = json_decode($data,true,512,JSON_BIGINT_AS_STRING);
                $a = $res['data'][0]['tk_status'];
//                 dump($a);
//                   print_r($res);die;

                $error = isset($res['errcode'])?$res['errcode']:$res['error'];
                if($error){
                    return json(['msg'=>$error,'ok'=>false]);
                }else{

                    $result = $res['data'];

                    $arr = $arrs = [];
                    $i = 0;
                    if(!empty($result)){
                        foreach($result as $k=>$v){
                            if(strpos($v['site_name'],'买就省')!==false){
                                $arr['user_id'] = Db::name('pid')->where('adzone_id',$v['adzone_id'])->value('user_id');
                                $arr['create_time'] = $v['create_time'];
                                $arr['order_num'] = $v['trade_id'];//订单号
                                $arr['parent_order_num'] = $v['trade_parent_id'];//父订单号
                                $arr['goods_id'] = $v['num_iid'];
                                $arr['info'] = $v['item_title'];
                                $arr['shop'] = $v['seller_shop_title'];
                                $arr['nick'] = isset($v['seller_nick'])?$v['seller_nick']:'';//旺旺名
                                $arr['amount'] = $v['item_num'];
                                $arr['price'] = $v['price'];

                                //淘客订单状态，3：订单结算，12：订单付款， 13：订单失效，14：订单成功
                                if(intval($v['tk_status'])=='12'){
                                    $arr['state'] = 1;
                                }elseif(intval($v['tk_status'])=='3'){
                                    $arr['state'] = 2;
                                }elseif(intval($v['tk_status'])=='13'){
                                    $arr['state'] = 3;
                                }elseif(intval($v['tk_status'])=='14'){
                                    $arr['state'] = 4;
                                }else{
                                    $arr['state'] = 0;
                                }
                                $arr['income_rate'] = $v['income_rate'];//收入比率
                                $arr['divide_tate'] = $v['commission_rate']/100;//分成比率

                                $arr['pay'] = isset($v['pay_price'])?$v['pay_price']:$v['alipay_total_price'];//实际支付金额
                                $arr['effect'] = $v['pub_share_pre_fee'];//预估收入
                                $arr['settle'] = $v['alipay_total_price']?$v['alipay_total_price']:'0';

                                $arr['expect'] = $v['commission'];//佣金预计收入


                                $arr['finish_time'] = isset($v['earning_time'])?$v['earning_time']:'';
                                $arr['yj_rate'] = $v['total_commission_rate'];
                                $arr['yj_sum'] = isset($v['total_commission_fee'])?$v['total_commission_fee']:(round($arr['settle'] * ($v['total_commission_rate']), 2));;//佣金

                                $arr['member_actual'] = round(($v['commission']/2)*$arr['amount'],2);//会员佣金实际收入
                                $arr['member_expect'] = round(($arr['amount']*$arr['yj_rate']*$arr['settle'])/2,2);//预计会员佣金


                                $arr['subsidy_rate'] = $v['subsidy_rate'];
                                $arr['subsidy'] = isset($v['subsidy_fee'])?$v['subsidy_fee']:(round($arr['price'] * ($v['subsidy_rate']), 2));//补贴金额
                                $arr['goods_type'] = $v['auction_category'];

                                $arr['adzone_id'] = $v['adzone_id'];
                                $arr['adzone_name'] = $v['adzone_name'];

                                //订单用户添加
                                $userData = [
                                    'user_id'=>$arr['user_id'],
                                    'order_num'=> $arr['order_num'] ,
                                    'create_time'=>time()
                                ];
                                $check_user = Db::name('user_order')->where('order_num',$arr['order_num'])->find();
                                if(empty($check_user)){
                                    Db::name('user_order')->insert($userData);
                                }

                                if ($arr['state'] == 2) {
                                    //订单结算
                                    $user = Db::name('user')->where('id', $arr['user_id'])->find();
                                    $amount = round($v['total_commission_fee'] / 2,2);
                                    $a = [
                                        'user_id' => $arr['user_id'],
                                        'commission' => $amount,
                                        'time' => time(),
                                        'finish_time' => $arr['finish_time'],
                                        'order_num' => $arr['order_num'],
                                        'state' => 1,//1收入，2支出
                                        'type' => 1,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                        'remark' => '订单' . $arr['order_num'] . '收入'
                                    ];
                                    $check_profit = Db::name('profit')
                                        ->where('user_id', $arr['user_id'])
                                        ->where('remark', $arr['order_num'] )
                                        ->find();
                                    if (empty($check_profit)) {
                                        Db::name('profit')->insert($a);
                                        Db::name('user')->where('id',$arr['user_id'])->setInc('total',$amount);
                                        Db::name('user')->where('id',$arr['user_id'])->setInc('commission',$amount);
                                    }
                                    $parent_id = $user['parent_id'];
                                    if($parent_id){
                                        $parent = Db::name('user')->where('id',$parent_id)->find();
                                        $ticheng = 0;
                                        if($parent['status']==3||$parent['status']==4){
                                            $rule = Db::name('partner_rule')->where('status',$parent['status'])->find();
                                            $level1 = $rule['level1']/100;
                                            $ticheng = round($amount*$level1,2);
                                        }

                                        $arr1 = [
                                            'user_id' => $parent_id,
                                            'commission' => $ticheng,
                                            'time' => time(),
                                            'finish_time' => $arr['finish_time'],
                                            'order_num' => $arr['order_num'],
                                            'state' => 1,//1收入，2支出
                                            'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                            'remark' => '粉丝' . $parent_id . '订单' . $arr['order_num'] . '收入'
                                        ];
                                        $check_profit = Db::name('profit')
                                            ->where('user_id', $parent_id)
                                            ->where('order_num',  $arr['order_num'])
                                            ->find();
                                        if (empty($check_profit)) {
                                            Db::name('profit')->insert($arr1);
                                            Db::name('user')->where('id',$parent_id)->setInc('total',$ticheng);
                                            Db::name('user')->where('id',$parent_id)->setInc('commission',$ticheng);
                                            Db::name('user')->where('id',$parent_id)->setInc('rebate',$ticheng);
                                        }
                                        $grandsire = Db::name('user')->where('id',$parent['parent_id'])->find();
                                        if($grandsire){
                                            //祖籍
                                            $t2 = 0;
                                            if($grandsire['status']==3||$grandsire['status']==4){
                                                $rule = Db::name('partner_rule')->where('status',$grandsire['status'])->find();
                                                $level2 = $rule['level2']/100;
                                                $t2 = round($amount*$level2,2);
                                            }

                                            $arr2 = [
                                                'user_id' => $grandsire['id'],
                                                'commission' => $t2,
                                                'time' => time(),
                                                'finish_time' => $arr['finish_time'],
                                                'order_num' => $arr['order_num'],
                                                'state' => 1,//1收入，2支出
                                                'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                                'remark' => '粉丝' . $grandsire['id'] . '订单' . $arr['order_num'] . '收入'
                                            ];
                                            $check_profit = Db::name('profit')
                                                ->where('user_id', $grandsire['id'])
                                                ->where('order_num', $arr['order_num'])
                                                ->find();
                                            if (empty($check_profit)) {
                                                Db::name('profit')->insert($arr2);
                                                Db::name('user')->where('id',$grandsire['id'])->setInc('total',$t2);
                                                Db::name('user')->where('id',$grandsire['id'])->setInc('commission',$t2);
                                                Db::name('user')->where('id',$grandsire['id'])->setInc('rebate',$t2);
                                            }

                                        }
                                    }

                                }

                                $check = Db::name('goods_order')
                                    ->where('goods_id',$arr['goods_id'])
                                    ->where('order_num',$arr['order_num'])
                                    ->find();
                                if ($check) {
                                    $success = Db::name('goods_order')
                                        ->where('goods_id', $arr['goods_id'])
                                        ->where('order_num', $arr['order_num'])
                                        ->update($arr);
//                                        $e = 'success:'.$success.'条';
//                                   return json(['msg'=>$e,'ok'=>true]);
                                } else {
                                    $arrs[] = $arr;
                                }
                                $i++;

                            }

                        }

                        Db::startTrans();
                        try{
                            $success = 0;
                            foreach($arrs as $k=>$v){
                                $check = Db::name('goods_order')
                                    ->where('goods_id',$v['goods_id'])
                                    ->where('order_num',$v['order_num'])
                                    ->find();

                                if(empty($check)){
                                    $success = Db::name('goods_order')->insertAll($arrs); //批量插入数据

//                                   $e = '插入:'.$success.'条';
//                                   return json(['msg'=>$e,'ok'=>true]);
                                }else{
                                    $success = 0;
                                }

                            }

                            foreach($arrs as $k =>$v){

                                if ($v['state'] == 2) {
                                    //订单结算
                                    $user = Db::name('user')->where('id', $v['user_id'])->find();
                                    $amount = round($v['yj_sum'] / 2,2);
                                    $arr = [
                                        'user_id' => $v['user_id'],
                                        'commission' => $amount,
                                        'order_num' => $v['order_num'],
                                        'time' => time(),
                                        'finish_time' => $v['finish_time'],
                                        'state' => 1,//1收入，2支出
                                        'type' => 1,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                        'remark' => '订单' . $v['order_num'] . '收入'
                                    ];
                                    $check_profit = Db::name('profit')
                                        ->where('user_id', $v['user_id'])
                                        ->where('order_num', $v['order_num'] )
                                        ->find();
                                    if (empty($check_profit)) {
                                        Db::name('profit')->insert($arr);
                                        Db::name('user')->where('id',$v['user_id'])->setInc('total',$amount);
                                        Db::name('user')->where('id',$v['user_id'])->setInc('commission',$amount);
                                    }
                                    $parent_id = $user['parent_id'];
                                    if($parent_id){
                                        $parent = Db::name('user')->where('id',$parent_id)->find();
                                        $ticheng = 0;
                                        if($parent['status']==3||$parent['status']==4){
                                            $rule = Db::name('partner_rule')->where('status',$parent['status'])->find();
                                            $level1 = $rule['level1']/100;
                                            $ticheng = round($amount*$level1,2);
                                        }
                                        $arr1 = [
                                            'user_id' => $parent_id,
                                            'commission' => $ticheng,
                                            'order_num' => $v['order_num'],
                                            'time' => time(),
                                            'finish_time' => $v['finish_time'],
                                            'state' => 1,//1收入，2支出
                                            'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                            'remark' => '粉丝' . $v['user_id'] . '订单' . $v['order_num'] . '收入'
                                        ];
                                        $check_profit = Db::name('profit')
                                            ->where('user_id', $parent_id)
                                            ->where('order_num', $v['order_num'] )
                                            ->find();
                                        if (empty($check_profit)) {
                                            Db::name('profit')->insert($arr1);
                                            Db::name('user')->where('id',$parent_id)->setInc('total',$ticheng);
                                            Db::name('user')->where('id',$parent_id)->setInc('commission',$ticheng);
                                            Db::name('user')->where('id',$parent_id)->setInc('rebate',$ticheng);
                                        }
                                        $grandsire = Db::name('user')->where('id',$parent['parent_id'])->find();
                                        if($grandsire){
                                            //祖籍
                                            $t2 = 0;
                                            if($grandsire['status']==3||$grandsire['status']==4){
                                                $rule = Db::name('partner_rule')->where('status',$grandsire['status'])->find();
                                                $level2 = $rule['level2']/100;
                                                $t2 = round($amount*$level2,2);
                                            }
                                            $arr2 = [
                                                'user_id' => $grandsire['id'],
                                                'commission' => $t2,
                                                'order_num' => $v['order_num'],
                                                'time' => time(),
                                                'finish_time' => $v['finish_time'],
                                                'state' => 1,//1收入，2支出
                                                'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                                'remark' => '粉丝' . $v['user_id'] . '订单' . $v['order_num'] . '收入'
                                            ];
                                            $check_profit = Db::name('profit')
                                                ->where('user_id', $grandsire['id'])
                                                ->where('order_num', $v['order_num'] )
                                                ->find();
                                            if (empty($check_profit)) {
                                                Db::name('profit')->insert($arr2);
                                                Db::name('user')->where('id',$grandsire['id'])->setInc('total',$t2);
                                                Db::name('user')->where('id',$grandsire['id'])->setInc('commission',$t2);
                                                Db::name('user')->where('id',$grandsire['id'])->setInc('rebate',$t2);
                                            }

                                        }
                                    }

                                }



                            }

                            // 提交事务
                            Db::commit();
//                            $e = '插入:'.$success.'条';
//                            return json(['msg'=>$e,'ok'=>true]);
                        } catch (\Exception $e) {
                            // 回滚事务
                            Db::rollback();
                            return json(['msg'=>$e,'ok'=>false]);
                        }

                    }


                }


            }


        }
    }



    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * 我的统计
     * 本月预估收入
     * 今日佣金
     * 累计收益
     */
    public function count(){
        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'token不能为空','ok'=>false]);
        }
        $user    = model('User')->getUser($token);
        $user_id = $user['id'];
        $res = Db::name('user')->where('id',$user_id)->value('total');

        $rule = Db::name('rebate_rule')->where('us_id',$user['status'])->find();
        $level1 = $rule['level1']/100;
        $level2 = $rule['level2']/100;

        //本月
        $BeginDate = date('Y-m-01', strtotime(date("Y-m-d")));//当月第一天
        $end1 = date('Y-m-d', strtotime("$BeginDate +1 month -1 day"));//当月最后一天
        $end = $end1." 23:59:59";//当月最后一天

        //本月预估佣金
        $same_total = model('User')->get_last_predict($BeginDate,$end,$user_id,$level1,$level2,$user);

        $BeginDate = date('Y-m-d');
        $endDate   = $BeginDate." 23:59:59";

        $yj  = model('User')->getYj($token,$BeginDate,$endDate);
        return json([
            'msg'=>'请求成功',
            'ok'=>true,
            'total'=>$res,//累计收益
            'same_total'=>$same_total,//本月预估收入
            'yj'=>$yj//今日佣金
        ]);


    }

    /**
     * 规则说明
     */
    public function rule(){
        $res = Db::name('profit_rule')->find();
        if($res){
            return json(['msg'=>'请求成功','ok'=>true,'data'=>$res]);
        }else{
            return json(['msg'=>'暂无数据','ok'=>false]);
        }
    }




}